package com.chunxiadong.controller.admin;

import com.chunxiadong.entity.Type;
import com.chunxiadong.service.TypeService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @auther QiuShangcheng
 * @create 2021/6/6
 */
@Controller
@RequestMapping("/admin/type")
public class TypeController {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    TypeService typeService;

    /**
     * 跳转到添加/分类管理页面
     * @param model
     * @return
     */
    @RequestMapping("/input")
    public String inputType(Model model){
        model.addAttribute("type", new Type());
        return "admin/type-input";
    }

    /**
     * 添加分类
     * @param type
     * @param attributes
     * @return
     */
    @RequestMapping("/addType")
    public String addType(Type type, RedirectAttributes attributes){
        Type t1 = typeService.getType(type.getId());
        if (t1 != null){
            attributes.addFlashAttribute("type_message","Do not add type repeatedly!");
            log.info(type.toString() + "\nResult : {" + " Add_Type repeatedly!" + "}");
            return "redirect:/admin/type/input";
        }
       typeService.addType(type);
        attributes.addFlashAttribute("type_message","AddType Successful!");
        return "redirect:/admin/type";
    }

    //    跳转修改分类页面
    @GetMapping("/{id}/input")
    public String inputUpdateType(@PathVariable Integer id, Model model) {
        model.addAttribute("type", typeService.getType(id));
        return "admin/type-input";
    }

    //    删除分类
    @GetMapping("/{id}/delete")
    public String deleteType(@PathVariable Integer id,RedirectAttributes attributes) {
        typeService.deleteType(id);
        attributes.addFlashAttribute("type_message", "Delete_Type Successful!");
        return "redirect:/admin/type";
    }

    //    编辑修改分类
    @PostMapping("/{id}")
    public String updateType( Type type, RedirectAttributes attributes) {
        Type t1 = typeService.getType(type.getId());
        if (t1 == null) {
            attributes.addFlashAttribute("type_message", "No Type_Data!");
            log.info(type.toString() + "\nResult : {" + " No Type_Data!" + "}");
            return "redirect:/admin/type/input";
        }
            typeService.updateType(type);
            attributes.addFlashAttribute("type_message", "Update_Type Successful!");
        return "redirect:/admin/type";
    }


}
